import 'dart:convert';
import 'dart:developer' as developer;
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'ring_service.dart';

/// 设备存储服务
/// 负责管理设备信息的持久化存储和自动重连
class DeviceStorageService extends GetxService {
  static const String _tag = 'DeviceStorageService';
  
  // 存储键名
  static const String _keyLastConnectedDevice = 'last_connected_device';
  static const String _keyCurrentDeviceSn = 'current_device_sn';
  static const String _keyAutoReconnectEnabled = 'auto_reconnect_enabled';
  static const String _keyConnectionHistory = 'connection_history';
  
  late final SharedPreferences _prefs;
  
  // 响应式状态
  final RxBool _autoReconnectEnabled = true.obs;
  final Rx<RingDevice?> _lastConnectedDevice = Rx<RingDevice?>(null);
  final RxString _currentDeviceSn = ''.obs;
  
  // Getters
  bool get autoReconnectEnabled => _autoReconnectEnabled.value;
  RingDevice? get lastConnectedDevice => _lastConnectedDevice.value;
  String get currentDeviceSn => _currentDeviceSn.value;
  RxBool get autoReconnectEnabledRx => _autoReconnectEnabled;
  Rx<RingDevice?> get lastConnectedDeviceRx => _lastConnectedDevice;
  RxString get currentDeviceSnRx => _currentDeviceSn;

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializeStorage();
    developer.log('💾 设备存储服务初始化完成', name: _tag);
  }

  /// 初始化存储
  Future<void> _initializeStorage() async {
    try {
      _prefs = await SharedPreferences.getInstance();
      
      // 加载之前保存的设备信息
      await _loadStoredDevice();
      
      // 加载自动重连设置
      _autoReconnectEnabled.value = _prefs.getBool(_keyAutoReconnectEnabled) ?? true;
      
      developer.log('✅ 存储初始化成功', name: _tag);
    } catch (e) {
      developer.log('❌ 存储初始化失败: $e', name: _tag);
    }
  }
  
  /// 加载存储的设备信息
  Future<void> _loadStoredDevice() async {
    try {
      final deviceJson = _prefs.getString(_keyLastConnectedDevice);
      if (deviceJson != null && deviceJson.isNotEmpty) {
        final deviceMap = jsonDecode(deviceJson) as Map<String, dynamic>;
        _lastConnectedDevice.value = RingDevice.fromMap(deviceMap);
        developer.log('📱 已加载存储的设备: ${_lastConnectedDevice.value?.name}', name: _tag);
      } else {
        developer.log('ℹ️ 没有存储的设备信息', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 加载存储设备信息失败: $e', name: _tag);
    }
  }
  

  /// 保存设备连接信息
  Future<void> saveConnectedDevice(RingDevice device) async {
    try {
      _lastConnectedDevice.value = device;
      
      // 保存设备信息到本地存储
      final deviceJson = jsonEncode({
        'name': device.name,
        'address': device.address,
        'rssi': device.rssi,
        'scanRecord': device.scanRecord,
      });
      
      await _prefs.setString(_keyLastConnectedDevice, deviceJson);
            
      developer.log('💾 设备信息已保存: ${device.name} (${device.address})', name: _tag);
    } catch (e) {
      developer.log('❌ 保存设备信息失败: $e', name: _tag);
    }
  }

  /// 清除设备连接信息
  Future<void> clearConnectedDevice() async {
    try {
      _lastConnectedDevice.value = null;
      await _prefs.remove(_keyLastConnectedDevice);
      developer.log('🗑️ 设备连接信息已清除', name: _tag);
    } catch (e) {
      developer.log('❌ 清除设备信息失败: $e', name: _tag);
    }
  }

  /// 检查是否有可自动重连的设备
  bool hasStoredDevice() {
    return _lastConnectedDevice.value != null && _autoReconnectEnabled.value;
  }

  /// 获取存储的设备地址
  String? getStoredDeviceAddress() {
    return _lastConnectedDevice.value?.address;
  }

  /// 获取存储的设备名称
  String? getStoredDeviceName() {
    return _lastConnectedDevice.value?.name;
  }

  /// 验证存储的设备信息是否有效
  bool isStoredDeviceValid() {
    final device = _lastConnectedDevice.value;
    return device != null && 
           device.address.isNotEmpty && 
           device.name.isNotEmpty;
  }

  /// 清除所有存储数据
  Future<void> clearAllData() async {
    try {
      await _prefs.remove(_keyLastConnectedDevice);
      await _prefs.remove(_keyAutoReconnectEnabled);
      await _prefs.remove(_keyConnectionHistory);
      
      _lastConnectedDevice.value = null;
      _autoReconnectEnabled.value = true;
      
      developer.log('🗑️ 所有设备存储数据已清除', name: _tag);
    } catch (e) {
      developer.log('❌ 清除所有数据失败: $e', name: _tag);
    }
  }
}
